module.exports = (sequelize, DataTypes) => {
  const Image = sequelize.define('Image', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    diary_id: {
      type: DataTypes.INTEGER,
      allowNull: true, // 允许为空，因为图片可能不关联特定日记（如富文本编辑器上传的图片）
      references: {
        model: 'diaries',
        key: 'id'
      }
    },
    filename: {
      type: DataTypes.STRING(255),
      allowNull: false,
      validate: {
        notEmpty: true
      }
    },
    original_name: {
      type: DataTypes.STRING(255),
      allowNull: false,
      validate: {
        notEmpty: true
      }
    },
    file_path: {
      type: DataTypes.STRING(500),
      allowNull: false,
      validate: {
        notEmpty: true
      }
    },
    file_size: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        min: 1
      },
      comment: '文件大小(字节)'
    },
    mime_type: {
      type: DataTypes.STRING(100),
      allowNull: false,
      validate: {
        notEmpty: true
      }
    },
    width: {
      type: DataTypes.INTEGER,
      allowNull: true,
      validate: {
        min: 1
      },
      comment: '图片宽度'
    },
    height: {
      type: DataTypes.INTEGER,
      allowNull: true,
      validate: {
        min: 1
      },
      comment: '图片高度'
    },
    sort_order: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      validate: {
        min: 0
      },
      comment: '排序顺序'
    }
  }, {
    tableName: 'images',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: false, // 图片不需要更新时间
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['diary_id']
      },
      {
        fields: ['diary_id', 'sort_order']
      }
    ]
  });

  Image.associate = (models) => {
    // 图片属于用户
    Image.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user',
      onDelete: 'CASCADE'
    });

    // 图片属于日记
    Image.belongsTo(models.Diary, {
      foreignKey: 'diary_id',
      as: 'diary',
      onDelete: 'CASCADE'
    });
  };

  // 实例方法：获取图片URL
  Image.prototype.getImageUrl = function() {
    return `/uploads/${this.filename}`;
  };

  // 实例方法：获取图片大小格式化字符串
  Image.prototype.getFormattedSize = function() {
    const size = this.file_size;
    if (size < 1024) {
      return `${size} B`;
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    }
  };

  return Image;
}; 